﻿using MiniFox.Web;
using Newtonsoft.Json;
using System.Net.Mime;
using System.Text;

namespace WebApi.Test
{
    /// <summary>
    /// 
    /// </summary>
    public static class UriExtensions
    {
        public const string DS_URI = "http://localhost:5113";
        public static async Task<string> GetAsync(this string uri)
        {
            Console.WriteLine($"****** Begin GET: {uri}");
            var responseContent = await new Uri(uri).HttpGetAsync();
            string responseBody = await responseContent.ReadAsStringAsync();
            Console.WriteLine($"响应");
            Console.WriteLine(responseBody);
            Console.WriteLine($"****** End GET: {uri}");
            return responseBody;
        }
        public static async Task<string> PostAsync(this string uri, string requestBody)
        {
            StringContent content = new StringContent(requestBody, Encoding.UTF8, MediaTypeNames.Application.Json);
            Console.WriteLine($"****** Begin POST: {uri}");
            Console.WriteLine("报文主体");
            Console.WriteLine(requestBody);
            var responseContent = await new Uri(uri).HttpPostAsync(content);
            string responseBody = await responseContent.ReadAsStringAsync();
            Console.WriteLine($"响应");
            Console.WriteLine(responseBody);
            Console.WriteLine($"****** End POST: {uri}");
            return responseBody;
        }

        public static async Task<RS> GetAsync<RS>(this string uri)
        {
            string json = await uri.GetAsync();
            RS responseObj = JsonConvert.DeserializeObject<RS>(json);
            return responseObj;
        }
        public static async Task<RS> PostAsync<RQ, RS>(this string uri, RQ requestObj)
        {
            string json = await uri.PostAsync(JsonConvert.SerializeObject(requestObj));
            RS responseObj = JsonConvert.DeserializeObject<RS>(json);
            return responseObj;

        }
    }
}
